package com.enation.app.javashop.core.promotion.shetuan.service.impl;

import com.alibaba.fastjson.JSON;
import com.enation.app.javashop.core.base.CachePrefix;
import com.enation.app.javashop.core.base.message.ShetuanChangeMsg;
import com.enation.app.javashop.core.base.rabbitmq.AmqpExchange;
import com.enation.app.javashop.core.client.member.ShopCatClient;
import com.enation.app.javashop.core.goods.model.dos.GoodsDO;
import com.enation.app.javashop.core.goods.model.dos.GoodsSkuDO;
import com.enation.app.javashop.core.goods.model.dto.BuyRecord;
import com.enation.app.javashop.core.goods.model.enums.Permission;
import com.enation.app.javashop.core.goods.model.vo.GoodsSkuVO;
import com.enation.app.javashop.core.goods.service.GoodsManager;
import com.enation.app.javashop.core.goods.service.GoodsQueryManager;
import com.enation.app.javashop.core.goods.service.GoodsSkuManager;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.promotion.groupbuy.model.enums.GroupbuyQuantityLogEnum;
import com.enation.app.javashop.core.promotion.seckill.model.vo.SeckillGoodsVO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsVO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanbuyQuantityLog;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanGoodsStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.model.vo.QueryShetuanGoodsVO;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanGoodsManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanbuyQuantityLogManager;
import com.enation.app.javashop.core.promotion.tool.model.dto.PromotionDTO;
import com.enation.app.javashop.core.promotion.tool.model.enums.PromotionTypeEnum;
import com.enation.app.javashop.core.promotion.tool.service.PromotionGoodsManager;
import com.enation.app.javashop.core.promotion.tool.support.SkuNameUtil;
import com.enation.app.javashop.core.shop.model.dos.ShopCatDO;
import com.enation.app.javashop.core.shop.model.vo.ShopCatItem;
import com.enation.app.javashop.core.trade.order.model.vo.OrderSkuVO;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.security.model.Seller;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.SqlUtil;
import com.enation.app.javashop.framework.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 拼团业务类
 *
 * @author admin
 * @version vv1.0.0
 * @since vv7.1.0
 * 2019-01-21 15:17:57
 */
@Service
public class ShetuanGoodsManagerImpl implements ShetuanGoodsManager {
    private static Logger logger = LoggerFactory.getLogger(ShetuanGoodsManagerImpl.class);
    @Autowired
    @Qualifier("tradeDaoSupport")
    private DaoSupport tradeDaoSupport;


    @Override
    public ShetuanGoodsDO getById(Integer id) {
        return this.tradeDaoSupport.queryForObject(ShetuanGoodsDO.class, id);
    }

    @Override
    public Page<ShetuanGoodsDO> getPageForMap(Map map, int pageNo, int pageSize) {
        StringBuffer sql = new StringBuffer("select * from es_shetuan_goods where status!=" + ShetuanGoodsStatusEnum.DELETE.getIndex());
        if (map != null && map.size() > 0) {
            sql.append(" and  ");
            Object[] objs = new Object[map.size()];
            int i = 0;
            for (Object obj : map.keySet()) {
                sql.append(obj).append("= ?");
                objs[i++] = map.get(obj);
            }
            return this.tradeDaoSupport.queryForPage(sql.toString(), pageNo, pageSize, objs);
        } else {
            return this.tradeDaoSupport.queryForPage(sql.toString(), pageNo, pageSize);
        }

    }

    @Override
    public ShetuanGoodsVO getBySkuId(Integer shetuanId, Integer skuId) {
        String sql = "select *,sg.id shetuan_goods_id from es_shetuan_goods  sg left join es_shetuan st ON sg.shetuan_id=st.shetuan_id where sg.status=" + ShetuanGoodsStatusEnum.ON_LINE.getIndex() + " and sg.sku_id=?  and sg.shetuan_id=?  limit 1";
        ShetuanGoodsVO shetuanGoodsVO = tradeDaoSupport.queryForObject(sql, ShetuanGoodsVO.class, skuId, shetuanId);
        if(shetuanGoodsVO!=null){
            shetuanGoodsVO.countTime();
        }
        return shetuanGoodsVO;
    }


    @Override
    public ShetuanGoodsVO getShetuanGoodsDetail(Integer shetuanGoodsId) {
        String sql = "select *,st.status shetuan_status,sg.id shetuan_goods_id from es_shetuan_goods  sg left join es_shetuan st ON sg.shetuan_id=st.shetuan_id where sg.id=? limit 1";
        ShetuanGoodsVO shetuanGoodsVO = tradeDaoSupport.queryForObject(sql, ShetuanGoodsVO.class, shetuanGoodsId);
        return shetuanGoodsVO;
    }


    @Override
    public List<ShetuanGoodsDO> queryShetuanGoodsBySkuIds(Integer shetuanId, List<Integer> skuIds) {
        List<Object> term = new ArrayList<>();
        String str = SqlUtil.getInSql(skuIds.toArray(), term);
        if (skuIds == null || term.size() == 0) {
            return new ArrayList<>();
        }
        term.add(shetuanId);
        // 社区团购商品
        String sql = "select * from es_shetuan_goods  where sku_id in(" + str + ") and shetuan_id=?";
        List<ShetuanGoodsDO> shetuanGoodsDOS = tradeDaoSupport.queryForList(sql, ShetuanGoodsDO.class, term.toArray());
        return shetuanGoodsDOS;
    }

    @Override
    public List<ShetuanGoodsDO> queryShetuanGoodsByIds(List<Integer> ids) {
        List<Object> term = new ArrayList<>();
        String str = SqlUtil.getInSql(ids.toArray(), term);
        if (ids == null || term.size() == 0) {
            return new ArrayList<>();
        }
        // 已上线社区团购商品
        String sql = "select * from es_shetuan_goods  where status=" + ShetuanGoodsStatusEnum.ON_LINE.getIndex() + " and id in(" + str + ") ";
        List<ShetuanGoodsDO> shetuanGoodsDOS = tradeDaoSupport.queryForList(sql, ShetuanGoodsDO.class, term.toArray());
        return shetuanGoodsDOS;
    }

    @Override
    public Page<ShetuanGoodsVO> queryByPage(QueryShetuanGoodsVO queryShetuanGoodsVO) {
        List<Object> term = new ArrayList<>();
        StringBuffer sql = new StringBuffer("select sku.enable_quantity, sg.* from es_shetuan_goods sg left join es_goods_sku sku on sg.sku_id=sku.sku_id where sg.status!=" + ShetuanGoodsStatusEnum.DELETE.getIndex());
        if (queryShetuanGoodsVO.getShetuanId() != null) {
            sql.append(" and  sg.shetuan_id=?");
            term.add(queryShetuanGoodsVO.getShetuanId());
        }
        // 商品名称
        if (queryShetuanGoodsVO.getKeyword() != null) {
            sql.append(" and  sg.goods_name like ? ");
            term.add("%"+queryShetuanGoodsVO.getKeyword()+"%");
        }
        // 店铺分组
        Integer shopCatId = queryShetuanGoodsVO.getShopCatId();
        if (shopCatId != null) {
            sql.append(" and sg.shop_cat_items like  ? ");
            term.add("%" + shopCatId +"%");
        }
        // 商品上下架状态  40 下架 50 上架   ShetuanGoodsStatusEnum
        String status = queryShetuanGoodsVO.getStatus();
        if (StringUtil.notEmpty(status)) {
            sql.append(" and  sg.status = ? ");
            term.add(status);
        }

        // 参团数量
        Integer goodsNum = queryShetuanGoodsVO.getGoodsNum();
        if(goodsNum != null){
            sql.append(" and  sg.goods_num = ? ");
            term.add(goodsNum);
        }

        if (StringUtil.notEmpty(queryShetuanGoodsVO.getGoodsIds())) {
            String goodsIds = queryShetuanGoodsVO.getGoodsIds();
            if (goodsIds.indexOf("，") > 0) {
                goodsIds = goodsIds.replaceAll("，", ",");
            }
            sql.append(" and sg.goods_id in (" + goodsIds + ")");
        }

        //增加排序
        String sortField = queryShetuanGoodsVO.getSortFiled();
        if(StringUtil.notEmpty(sortField)){
            String[] sortar = sortField.split("_");
            sql.append(" order by sg."+sortar[0]+" "+ sortar[1]);
        }else{
            // 默认排序
            sql.append(" order by  sg.create_time  desc ");
        }
        return this.tradeDaoSupport.queryForPage(sql.toString(), queryShetuanGoodsVO.getPageNo(), queryShetuanGoodsVO.getPageSize(), ShetuanGoodsVO.class, term.toArray());
    }

    @Override
    public List<ShetuanGoodsDO> getOverlapGoods(List<ShetuanGoodsDO> goodsList, List<ShetuanDO> shetuanDOS) {
        List<Integer> skuIds = goodsList.stream().map(ShetuanGoodsDO::getSkuId).collect(Collectors.toList());
        List<Integer> shetuanIds = shetuanDOS.stream().map(ShetuanDO::getShetuanId).collect(Collectors.toList());
        List<Object> term = new ArrayList<>();
        String str1 = SqlUtil.getInSql(skuIds.toArray(), term);
        if (skuIds == null ||shetuanIds == null || term.size() == 0) {
            return new ArrayList<>();
        }

        StringBuilder sql = new StringBuilder("select  *  from es_shetuan_goods  where sku_id in (" + str1 + ") and status=" + ShetuanGoodsStatusEnum.ON_LINE.getIndex());
        if(!CollectionUtils.isEmpty(shetuanDOS)){
            String str2 = SqlUtil.getInSql(shetuanIds.toArray(), term);
            sql.append(" and  shetuan_id in (" + str2 + ") ");
        }
        List<ShetuanGoodsDO> shetuanGoods = this.tradeDaoSupport.queryForList(sql.toString(),ShetuanGoodsDO.class, term.toArray());
        return shetuanGoods;
    }

    @Override
    public List<ShetuanGoodsDO> querySheuanGoodsByGoodsIds(Integer[] goodsIds) {
        List<Object> term = new ArrayList<>();
        String str1 = SqlUtil.getInSql(goodsIds, term);

        String sql = "select sg.* from es_shetuan_goods  sg left join es_shetuan st ON sg.shetuan_id=st.shetuan_id where st.status="+ ShetuanStatusEnum.ON_LINE.getIndex() +" and sg.status=" + ShetuanGoodsStatusEnum.ON_LINE.getIndex() + " and sg.goods_id in (" + str1 + ") ";
        List<ShetuanGoodsDO> shetuanGoods = tradeDaoSupport.queryForList(sql, ShetuanGoodsDO.class, term.toArray());
        return shetuanGoods;
    }

    @Override
    public List<ShetuanGoodsDO> getByShetuanId(Integer shetuanId) {
        // 已上线社区团购商品
        String sql = "select * from es_shetuan_goods  where status=" + ShetuanGoodsStatusEnum.ON_LINE.getIndex() + " and shetuan_id =?";
        return tradeDaoSupport.queryForList(sql, ShetuanGoodsDO.class, shetuanId);
    }

    @Override
    public List<ShetuanGoodsDO> getBySkuIds(List<Integer> skuIds, int status) {
        List<Object> term = new ArrayList<>();
        String str1 = SqlUtil.getInSql(skuIds.toArray(), term);
        String sql = "select * from es_shetuan_goods where status=" + status + " and sku_id in (" + str1 + ") ";

        return tradeDaoSupport.queryForList(sql, ShetuanGoodsDO.class, term.toArray());
    }

    @Override
    public ShetuanGoodsDO checkIsShetuan(Integer skuId, Integer activityId) {
        if (skuId == null || activityId == null) {
            return null;
        }
        String sql = "select  sg.*  from es_promotion_goods pg left join es_shetuan_goods sg on pg.product_id=sg.sku_id and pg.shetuan_id=sg.activity_id where pg.product_id =? and pg.activity_id=? and pg.promotion_type='" + PromotionTypeEnum.SHETUAN.name()+"'";
        ShetuanGoodsDO shetuanGoodsDO = this.tradeDaoSupport.queryForObject(sql, ShetuanGoodsDO.class, skuId, activityId);
        return shetuanGoodsDO;
    }


    @Override
    public List<ShetuanGoodsDO> getByShetuanAndStatus(Integer shetuanId, Integer[] statusArray) {
        StringBuffer in = new StringBuffer();
        int idx = 0;
        for (Integer status : statusArray) {
            idx++;
            in.append(status);
            if (idx != statusArray.length) {
                in.append(",");
            }
        }
        if (in.toString() == null || in.toString().equals("")) {
            String sql = "select * from es_shetuan_goods where shetuan_id=?";
            return this.tradeDaoSupport.queryForList(sql, ShetuanGoodsDO.class, shetuanId);
        } else {
            String sql = "select * from es_shetuan_goods where shetuan_id=? and status in (?)";
            return this.tradeDaoSupport.queryForList(sql, ShetuanGoodsDO.class, shetuanId, in.toString());
        }
    }
}
